﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace InterlockedDemo
{
    class Program
    {
        static object lockObj = new object();
        static int maxTask = 5;
        static int currentCount = 0;
        //假设要处理的数据源
        static List<int> numbers = Enumerable.Range(5, 10).ToList();
        private static Func<int> NewSystemByte;
        static void Main(string[] args)
        {
            try
            {

            }
            catch (Exception ex)
            {


            }


            var A = numbers;
            // TaskContinueDemo();

            // MainTest();

            DownLoad();

            // Test();

            int systemByte = Guid.NewGuid().GetHashCode();
            NewSystemByte = () => Interlocked.Increment(ref systemByte);


            Console.ReadKey();
        }

        private static void DownLoad()
        {
            DownLoadTest dwtest = new DownLoadTest();
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken token = cts.Token;
            var task1 = dwtest.DoRunTaskAsync("https://www.baidu.com/", token);
            var task2 = dwtest.DoRunTaskAsync("https://www.taobao.com/", token);
            var task3 = dwtest.DoRunTaskAsync("https://www.cnblogs.com/", token);
            Task[] tasks = new Task[] { task1, task2, task3 };
            Console.WriteLine("task.Result等待結果打印");
            Task.WaitAll(tasks, 10000);
            cts.Cancel();//超过10s时间取消运行
            Console.WriteLine(task1.Status);
            Console.WriteLine(task2.Status);
            Console.WriteLine(task3.Status);
            Console.WriteLine(string.Format("主線程運行結束"));
            Console.ReadKey();
        }

        public class DownLoadTest
        {
            Stopwatch watch = new Stopwatch();
            public DownLoadTest()
            {
                watch.Start();
            }

            public async Task DoRunTaskAsync(string url, CancellationToken ct)
            {
                if (ct.IsCancellationRequested)
                {
                    Console.WriteLine(string.Format("取消{0}的運行 :{1,4:N0}ms", url, watch.Elapsed.TotalMilliseconds));
                    return;
                }
                Console.WriteLine(string.Format("下載{0}開始運行 :{1,4:N0}ms", url, watch.Elapsed.TotalMilliseconds));
                WebClient wc = new WebClient();
                await Task.Run(() =>
                {
                    var task = wc.DownloadStringTaskAsync(url);
                    while (!task.IsCompleted)
                    {
                        if (ct.IsCancellationRequested)
                        {
                            Console.WriteLine(string.Format("取消{0}的運行 :{1,4:N0}ms", url, watch.Elapsed.TotalMilliseconds));
                            return;
                        }
                    }
                    if (task.IsCompleted)
                        Console.WriteLine(string.Format("下載{0}運行結束 :{1,4:N0}ms", url, watch.Elapsed.TotalMilliseconds));
                });
            }
        }


        static void Test()
        {

            int xx = 11;
            var kk = Interlocked.Increment(ref xx);

            int value = 10; int value2 = 20; int value3 = 30;

            //数值加一（原子性操作）
            //var a1 = Interlocked.Increment(ref value);
            ////数值减一（原子性操作）
            //var a2 = Interlocked.Decrement(ref value);
            //交换：把值2赋给值1；返回新值
            var a3 = Interlocked.Exchange(ref value, value2);
            //实现比较和交换两种功能：值1和值3比较，如果相同，把值2给值1，不相同则不作任何操作；返回原值（多用于判断条件）
            var a4 = Interlocked.CompareExchange(ref value, value2, value3);
        }


        static volatile int x, y, a, b;
        static void MainTest()
        {
            while (true)
            {
                var t1 = Task.Run(Test1);
                var t2 = Task.Run(Test2);

                Task.WaitAll(t1, t2);
                if (a == 0 && b == 0)
                {
                    Console.WriteLine("{0}, {1}", a, b);
                }

                x = y = a = b = 0;
            }
        }

        static void Test1()
        {
            x = 1;
            //按如下方式同步内存存取：执行当前线程的处理器在对指令重新排序时，
            //不能采用先执行 MemoryBarrier() 调用之后的内存存取，再执行 MemoryBarrier() 调用之前的内存存取的方式。Thread.MemoryBarrier 就是包装了它。

            //方案一 Interlocked.MemoryBarrier();
            //方案二 Interlocked.MemoryBarrierProcessWide();

            a = y;
        }

        static void Test2()
        {

            y = 1;

            //方案一 Interlocked.MemoryBarrier();
            b = x;

        }

        private static void TaskContinueDemo()
        {
            while (currentCount < maxTask && numbers.Count > 0)
            {
                lock (lockObj)
                {
                    if (currentCount < maxTask && numbers.Count > 0)
                    {
                        Interlocked.Increment(ref currentCount);//以原子操作的形式实现递增
                        var task = Task.Factory.StartNew(() =>
                        {
                            var number = numbers.FirstOrDefault();
                            if (number > 0)
                            {
                                numbers.Remove(number);
                                Thread.Sleep(1000);//假设执行一秒钟
                                Console.WriteLine("Task id {0} Time{1} currentCount{2} dealNumber{3}", Task.CurrentId, DateTime.Now, currentCount, number);
                                if (Rand() == 0)//模拟执行中异常
                                {
                                    numbers.Add(number);//因为出现异常，所以这里需要将number重新放入集合等待处理
                                    Console.WriteLine("number {0} add because Exception", number);
                                    throw new Exception();
                                }
                            }
                        }, TaskCreationOptions.LongRunning).ContinueWith(t =>
                        {//在ContinueWith中恢复计数
                            Interlocked.Decrement(ref currentCount);
                            Console.WriteLine("Continue Task id {0} Time{1} currentCount{2}", Task.CurrentId, DateTime.Now, currentCount);
                            TaskContinueDemo();
                        });
                    }
                }
            }
        }
        private static int Rand(int maxNumber = 5)
        {
            return Math.Abs(Guid.NewGuid().GetHashCode()) % maxNumber;
        }

    }
}
